<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: Random generator and text with OpenCV</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../d7/da8/tutorial_table_of_content_imgproc.html">Image Processing (imgproc module)</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">Random generator and text with OpenCV </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>Prev Tutorial:</b> <a class="el" href="../../d3/d96/tutorial_basic_geometric_drawing.html">Basic Drawing</a></p>
<p><b>Next Tutorial:</b> <a class="el" href="../../dc/dd3/tutorial_gausian_median_blur_bilateral_filter.html">Smoothing Images</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">Original author </td><td align="left">Ana Huamán </td></tr>
<tr>
<td align="right">Compatibility </td><td align="left">OpenCV &gt;= 3.0 </td></tr>
</table>
<h2>Goals </h2>
<p>In this tutorial you will learn how to:</p>
<ul>
<li>Use the <em>Random Number generator class</em> (<a class="el" href="../../d1/dd6/classcv_1_1RNG.html">cv::RNG</a> ) and how to get a random number from a uniform distribution.</li>
<li>Display text on an OpenCV window by using the function <a class="el" href="../../d6/d6e/group__imgproc__draw.html#ga5126f47f883d730f633d74f07456c576">cv::putText</a></li>
</ul>
<h2>Code </h2>
<ul>
<li>In the previous tutorial (<a class="el" href="../../d3/d96/tutorial_basic_geometric_drawing.html">Basic Drawing</a>) we drew diverse geometric figures, giving as input parameters such as coordinates (in the form of <a class="el" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">cv::Point</a>), color, thickness, etc. You might have noticed that we gave specific values for these arguments.</li>
<li>In this tutorial, we intend to use <em>random</em> values for the drawing parameters. Also, we intend to populate our image with a big number of geometric figures. Since we will be initializing them in a random fashion, this process will be automatic and made by using <em>loops</em> .</li>
<li>This code is in your OpenCV sample folder. Otherwise you can grab it from <a href="http://code.opencv.org/projects/opencv/repository/revisions/master/raw/samples/cpp/tutorial_code/core/Matrix/Drawing_2.cpp">here</a></li>
</ul>
<h2>Explanation </h2>
<ol type="1">
<li>Let's start by checking out the <em>main</em> function. We observe that first thing we do is creating a <em>Random Number Generator</em> object (RNG): <div class="fragment"><div class="line">RNG rng( 0xFFFFFFFF );</div></div><!-- fragment --> RNG implements a random number generator. In this example, <em>rng</em> is a RNG element initialized with the value <em>0xFFFFFFFF</em></li>
<li>Then we create a matrix initialized to <em>zeros</em> (which means that it will appear as black), specifying its height, width and its type: <div class="fragment"><div class="line">Mat image = Mat::zeros( window_height, window_width, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a> );</div><div class="line"></div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( window_name, image );</div></div><!-- fragment --></li>
<li>Then we proceed to draw crazy stuff. After taking a look at the code, you can see that it is mainly divided in 8 sections, defined as functions: <div class="fragment"><div class="line">c = Drawing_Random_Lines(image, window_name, rng);</div><div class="line"><span class="keywordflow">if</span>( c != 0 ) <span class="keywordflow">return</span> 0;</div><div class="line"></div><div class="line">c = Drawing_Random_Rectangles(image, window_name, rng);</div><div class="line"><span class="keywordflow">if</span>( c != 0 ) <span class="keywordflow">return</span> 0;</div><div class="line"></div><div class="line">c = Drawing_Random_Ellipses( image, window_name, rng );</div><div class="line"><span class="keywordflow">if</span>( c != 0 ) <span class="keywordflow">return</span> 0;</div><div class="line"></div><div class="line">c = Drawing_Random_Polylines( image, window_name, rng );</div><div class="line"><span class="keywordflow">if</span>( c != 0 ) <span class="keywordflow">return</span> 0;</div><div class="line"></div><div class="line">c = Drawing_Random_Filled_Polygons( image, window_name, rng );</div><div class="line"><span class="keywordflow">if</span>( c != 0 ) <span class="keywordflow">return</span> 0;</div><div class="line"></div><div class="line">c = Drawing_Random_Circles( image, window_name, rng );</div><div class="line"><span class="keywordflow">if</span>( c != 0 ) <span class="keywordflow">return</span> 0;</div><div class="line"></div><div class="line">c = Displaying_Random_Text( image, window_name, rng );</div><div class="line"><span class="keywordflow">if</span>( c != 0 ) <span class="keywordflow">return</span> 0;</div><div class="line"></div><div class="line">c = Displaying_Big_End( image, window_name, rng );</div></div><!-- fragment --> All of these functions follow the same pattern, so we will analyze only a couple of them, since the same explanation applies for all.</li>
<li>Checking out the function <b>Drawing_Random_Lines</b>: <div class="fragment"><div class="line"><span class="keywordtype">int</span> Drawing_Random_Lines( Mat image, <span class="keywordtype">char</span>* window_name, RNG rng )</div><div class="line">{</div><div class="line">  <span class="keywordtype">int</span> lineType = 8;</div><div class="line">  <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a> pt1, pt2;</div><div class="line"></div><div class="line">  <span class="keywordflow">for</span>( <span class="keywordtype">int</span> i = 0; i &lt; NUMBER; i++ )</div><div class="line">  {</div><div class="line">   pt1.<a class="code" href="../../db/d4e/classcv_1_1Point__.html#a4c96fa7bdbfe390be5ed356edb274ff3">x</a> = rng.uniform( x_1, x_2 );</div><div class="line">   pt1.y = rng.uniform( y_1, y_2 );</div><div class="line">   pt2.x = rng.uniform( x_1, x_2 );</div><div class="line">   pt2.y = rng.uniform( y_1, y_2 );</div><div class="line"></div><div class="line">   <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga7078a9fae8c7e7d13d24dac2520ae4a2">line</a>( image, pt1, pt2, randomColor(rng), rng.uniform(1, 10), 8 );</div><div class="line">   <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( window_name, image );</div><div class="line">   <span class="keywordflow">if</span>( <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>( DELAY ) &gt;= 0 )</div><div class="line">   { <span class="keywordflow">return</span> -1; }</div><div class="line">  }</div><div class="line">  <span class="keywordflow">return</span> 0;</div><div class="line">}</div></div><!-- fragment --> We can observe the following:<ul>
<li>The <em>for</em> loop will repeat <b>NUMBER</b> times. Since the function <a class="el" href="../../d6/d6e/group__imgproc__draw.html#ga7078a9fae8c7e7d13d24dac2520ae4a2">cv::line</a> is inside this loop, that means that <b>NUMBER</b> lines will be generated.</li>
<li>The line extremes are given by <em>pt1</em> and <em>pt2</em>. For <em>pt1</em> we can see that: <div class="fragment"><div class="line">pt1.x = rng.uniform( x_1, x_2 );</div><div class="line">pt1.y = rng.uniform( y_1, y_2 );</div></div><!-- fragment --><ul>
<li>We know that <b>rng</b> is a <em>Random number generator</em> object. In the code above we are calling <b>rng.uniform(a,b)</b>. This generates a randomly uniformed distribution between the values <b>a</b> and <b>b</b> (inclusive in <b>a</b>, exclusive in <b>b</b>).</li>
<li>From the explanation above, we deduce that the extremes <em>pt1</em> and <em>pt2</em> will be random values, so the lines positions will be quite impredictable, giving a nice visual effect (check out the Result section below).</li>
<li>As another observation, we notice that in the <a class="el" href="../../d6/d6e/group__imgproc__draw.html#ga7078a9fae8c7e7d13d24dac2520ae4a2">cv::line</a> arguments, for the <em>color</em> input we enter: <div class="fragment"><div class="line">randomColor(rng)</div></div><!-- fragment --> Let's check the function implementation: <div class="fragment"><div class="line"><span class="keyword">static</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a> randomColor( RNG&amp; rng )</div><div class="line">  {</div><div class="line">  <span class="keywordtype">int</span> icolor = (unsigned) rng;</div><div class="line">  <span class="keywordflow">return</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>( icolor&amp;255, (icolor&gt;&gt;8)&amp;255, (icolor&gt;&gt;16)&amp;255 );</div><div class="line">  }</div></div><!-- fragment --> As we can see, the return value is an <em>Scalar</em> with 3 randomly initialized values, which are used as the <em>R</em>, <em>G</em> and <em>B</em> parameters for the line color. Hence, the color of the lines will be random too!</li>
</ul>
</li>
</ul>
</li>
<li>The explanation above applies for the other functions generating circles, ellipses, polygons, etc. The parameters such as <em>center</em> and <em>vertices</em> are also generated randomly.</li>
<li>Before finishing, we also should take a look at the functions <em>Display_Random_Text</em> and <em>Displaying_Big_End</em>, since they both have a few interesting features:</li>
<li><p class="startli"><b>Display_Random_Text:</b> </p><div class="fragment"><div class="line"><span class="keywordtype">int</span> Displaying_Random_Text( Mat image, <span class="keywordtype">char</span>* window_name, RNG rng )</div><div class="line">{</div><div class="line">  <span class="keywordtype">int</span> lineType = 8;</div><div class="line"></div><div class="line">  <span class="keywordflow">for</span> ( <span class="keywordtype">int</span> i = 1; i &lt; NUMBER; i++ )</div><div class="line">  {</div><div class="line">    <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a> org;</div><div class="line">    org.<a class="code" href="../../db/d4e/classcv_1_1Point__.html#a4c96fa7bdbfe390be5ed356edb274ff3">x</a> = rng.uniform(x_1, x_2);</div><div class="line">    org.y = rng.uniform(y_1, y_2);</div><div class="line"></div><div class="line">    <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga5126f47f883d730f633d74f07456c576">putText</a>( image, <span class="stringliteral">&quot;Testing text rendering&quot;</span>, org, rng.uniform(0,8),</div><div class="line">             rng.uniform(0,100)*0.05+0.1, randomColor(rng), rng.uniform(1, 10), lineType);</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( window_name, image );</div><div class="line">    <span class="keywordflow">if</span>( <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>(DELAY) &gt;= 0 )</div><div class="line">      { <span class="keywordflow">return</span> -1; }</div><div class="line">  }</div><div class="line"></div><div class="line">  <span class="keywordflow">return</span> 0;</div><div class="line">}</div></div><!-- fragment --><p> Everything looks familiar but the expression: </p><div class="fragment"><div class="line"><a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga5126f47f883d730f633d74f07456c576">putText</a>( image, <span class="stringliteral">&quot;Testing text rendering&quot;</span>, org, rng.uniform(0,8),</div><div class="line">         rng.uniform(0,100)*0.05+0.1, randomColor(rng), rng.uniform(1, 10), lineType);</div></div><!-- fragment --><p> So, what does the function <a class="el" href="../../d6/d6e/group__imgproc__draw.html#ga5126f47f883d730f633d74f07456c576">cv::putText</a> do? In our example:</p><ul>
<li>Draws the text **"Testing text rendering"** in <b>image</b></li>
<li>The bottom-left corner of the text will be located in the Point <b>org</b></li>
<li>The font type is a random integer value in the range: \([0, 8&gt;\).</li>
<li>The scale of the font is denoted by the expression <b>rng.uniform(0, 100)x0.05 + 0.1</b> (meaning its range is: \([0.1, 5.1&gt;\))</li>
<li>The text color is random (denoted by <b>randomColor(rng)</b>)</li>
<li>The text thickness ranges between 1 and 10, as specified by <b>rng.uniform(1,10)</b></li>
</ul>
<p class="startli">As a result, we will get (analagously to the other drawing functions) <b>NUMBER</b> texts over our image, in random locations.</p>
</li>
<li><p class="startli"><b>Displaying_Big_End</b> </p><div class="fragment"><div class="line"><span class="keywordtype">int</span> Displaying_Big_End( Mat image, <span class="keywordtype">char</span>* window_name, RNG rng )</div><div class="line">{</div><div class="line">  <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a> textsize = <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga3d2abfcb995fd2db908c8288199dba82">getTextSize</a>(<span class="stringliteral">&quot;OpenCV forever!&quot;</span>, <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gga0f9314ea6e35f99bb23f29567fc16e11af7b1b25521fc9b5731a97cfd13460c2a">FONT_HERSHEY_COMPLEX</a>, 3, 5, 0);</div><div class="line">  <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a> org((window_width - textsize.width)/2, (window_height - textsize.height)/2);</div><div class="line">  <span class="keywordtype">int</span> lineType = 8;</div><div class="line"></div><div class="line">  Mat image2;</div><div class="line"></div><div class="line">  <span class="keywordflow">for</span>( <span class="keywordtype">int</span> i = 0; i &lt; 255; i += 2 )</div><div class="line">  {</div><div class="line">    image2 = image - Scalar::all(i);</div><div class="line">    <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga5126f47f883d730f633d74f07456c576">putText</a>( image2, <span class="stringliteral">&quot;OpenCV forever!&quot;</span>, org, <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gga0f9314ea6e35f99bb23f29567fc16e11af7b1b25521fc9b5731a97cfd13460c2a">FONT_HERSHEY_COMPLEX</a>, 3,</div><div class="line">           <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(i, i, 255), 5, lineType );</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( window_name, image2 );</div><div class="line">    <span class="keywordflow">if</span>( <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>(DELAY) &gt;= 0 )</div><div class="line">      { <span class="keywordflow">return</span> -1; }</div><div class="line">  }</div><div class="line"></div><div class="line">  <span class="keywordflow">return</span> 0;</div><div class="line">}</div></div><!-- fragment --><p> Besides the function <b>getTextSize</b> (which gets the size of the argument text), the new operation we can observe is inside the <em>foor</em> loop: </p><div class="fragment"><div class="line">image2 = image - Scalar::all(i)</div></div><!-- fragment --><p> So, <b>image2</b> is the subtraction of <b>image</b> and <b>Scalar::all(i)</b>. In fact, what happens here is that every pixel of <b>image2</b> will be the result of subtracting every pixel of <b>image</b> minus the value of <b>i</b> (remember that for each pixel we are considering three values such as R, G and B, so each of them will be affected)</p>
<p class="startli">Also remember that the subtraction operation <em>always</em> performs internally a <b>saturate</b> operation, which means that the result obtained will always be inside the allowed range (no negative and between 0 and 255 for our example).</p>
</li>
</ol>
<h2>Result </h2>
<p>As you just saw in the Code section, the program will sequentially execute diverse drawing functions, which will produce:</p>
<ol type="1">
<li><p class="startli">First a random set of <em>NUMBER</em> lines will appear on screen such as it can be seen in this screenshot:</p>
<div class="image">
<img src="../../Drawing_2_Tutorial_Result_0.jpg" alt="Drawing_2_Tutorial_Result_0.jpg"/>
</div>
</li>
<li>Then, a new set of figures, these time <em>rectangles</em> will follow.</li>
<li><p class="startli">Now some ellipses will appear, each of them with random position, size, thickness and arc length:</p>
<div class="image">
<img src="../../Drawing_2_Tutorial_Result_2.jpg" alt="Drawing_2_Tutorial_Result_2.jpg"/>
</div>
</li>
<li><p class="startli">Now, <em>polylines</em> with 03 segments will appear on screen, again in random configurations.</p>
<div class="image">
<img src="../../Drawing_2_Tutorial_Result_3.jpg" alt="Drawing_2_Tutorial_Result_3.jpg"/>
</div>
</li>
<li>Filled polygons (in this example triangles) will follow.</li>
<li><p class="startli">The last geometric figure to appear: circles!</p>
<div class="image">
<img src="../../Drawing_2_Tutorial_Result_5.jpg" alt="Drawing_2_Tutorial_Result_5.jpg"/>
</div>
</li>
<li>Near the end, the text *"Testing Text Rendering"* will appear in a variety of fonts, sizes, colors and positions.</li>
<li><p class="startli">And the big end (which by the way expresses a big truth too):</p>
<div class="image">
<img src="../../Drawing_2_Tutorial_Result_big.jpg" alt="Drawing_2_Tutorial_Result_big.jpg"/>
</div>
 </li>
</ol>
</div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:36 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
